<?php

namespace App\Http\Model;

use App\Http\Traits\DelayTask;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 用户账号注销
 */
class UserAccountCancel extends Base
{
    use DelayTask;

    /**
     * 表名字
     *
     * @var string
     */
    protected $table = 'user_account_cancel_log';

    /**
     * 构造函数
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 申请注销日志
     *
     * @param int $user_id 用户id
     * @param string $phone 手机号码
     * @return bool|int
     */
    public function createCancelLog(int $user_id, string $phone)
    {
        $expireTime = $this->getExpireTime();
        $cancelTime = date('Y-m-d H:i:s', time() + $expireTime);
        $cancelLog = DB::table($this->table)->where('user_id', $user_id)->first();
        if ($cancelLog) {
            // $this->delayedCallback($user_id);//延时任务
            return DB::table($this->table)->where('user_id', $user_id)->update([
                'mobile_phone' => $phone,
                'cancel_time' => $cancelTime,
                'will_be_deleted' => 0,
                'status' => 1
            ]);
        }

        // $this->delayedCallback($user_id);//延时任务
        return DB::table($this->table)->insert([
            'user_id' => $user_id,
            'mobile_phone' => $phone,
            'cancel_time' => $cancelTime,
            'created_time' => date('Y-m-d H:i:s', time()),
            'will_be_deleted' => 0,
            'status' => 1
        ]);
    }

    /**
     * 注销完成日志
     *
     * @param int $user_id 用户id
     * @param string $phone 手机号码
     * @return bool|int
     */
    public function createFinishCancelLog(int $user_id, string $phone)
    {
        return DB::table($this->table)->insert([
            'user_id' => $user_id,
            'mobile_phone' => $phone,
            'cancel_time' => date('Y-m-d H:i:s', time()),
            'created_time' => date('Y-m-d H:i:s', time()),
            'will_be_deleted' => 0,
            'status' => 2
        ]);
    }

    /**
     * 取消申请
     *
     * @param $user_id
     * @return int
     */
    public function updateCancelLog($user_id)
    {
        return DB::table($this->table)->where('user_id', $user_id)->update(['status' => 0]);
    }

    /**
     * 检测账号是否过期
     *
     * @param int $userId
     * @return bool
     */
    public function checkAccountIsOverdue(int $userId): bool
    {
        $record = self::query()->where('user_id', $userId)->get()->toArray();
        if (!$record) {
            return false;
        }

        $record = $record[0];
        if ($record['status'] == 0) {//已取消
            Log::info('checkAccountIsOverdue,status=0,record=' . json_encode($record));
            return false;
        }

        $userMobilePhone = User::query()->select(['mobile_phone'])->where('user_id', $userId)->value('mobile_phone');
        if ($userId == intval($userMobilePhone)) {//用户已被注销
            Log::info('checkAccountIsOverdue,user canceled,record=' . json_encode($record));
            return false;
        }

        $cancelTime = strtotime($record['cancel_time']);
        if ($cancelTime > time()) {
            Log::info('checkAccountIsOverdue,cancelTime<time,record=' . json_encode($record));
            return false;
        }

        Log::info('checkAccountIsOverdue,success,record=' . json_encode($record));
        return true;
    }

    /**
     * 注销用户
     *
     * @param int $userId
     * @return bool
     */
    public function cancelUser(int $userId)
    {
        $checkAccountIsOverdue = $this->checkAccountIsOverdue($userId);
        if (!$checkAccountIsOverdue) {
            return false;
        }

        User::query()->where('user_id', $userId)->update(['mobile_phone' => $userId]);
        (new UserVerify())->setResultEmpty($userId ,0 ,'注销');
        UserThirdpart::query()->where('user_id', $userId)->delete();//删除第三方登录记录

        (new Trends())->cleanUserTrends($userId);//删除动态
        (new Friends())->delFriendsFollowByUids([$userId]);//删除好友

        (new User())->removeAccountCancel($userId);//删除缓存
        DB::table($this->table)->where('user_id', $userId)->update(['status' => 2]);
        return true;
    }

    /**
     * 简易注销用户
     *
     * @param int $userId
     * @param int $isFull 1:删除全部记录;0删除基本信息
     * @return bool
     */
    public function simpleCancelUser(int $userId,$phone)
    {
        User::query()->where('user_id', $userId)->update(['mobile_phone' => $userId]);
        (new UserVerify())->setResultEmpty($userId ,0 ,'注销');
        UserThirdpart::query()->where('user_id', $userId)->delete();//删除第三方登录记录
        $this->createFinishCancelLog($userId,$phone);
        return true;
    }

    /**
     * 获取系统配置
     *
     * @return array|null
     */
    private function getSystemConfig()
    {
        return (new System())->get_config();
    }

    /**
     * 获取注销用户的过期时间
     *
     * @return int
     */
    public function getExpireTime(): int
    {
        $key = 'delete_user_expire_time';//单位：秒
        $systemConfig = $this->getSystemConfig();
        $value = $systemConfig[$key]['value'] ?: 24 * 3600 * 30;
        return intval($value);
    }

    /**
     * 延时回调，默认30天
     *
     * @param int $userId 用户id
     */
    private function delayedCallback(int $userId)
    {
        $this->delayTask('/user/delete_user/callback?user_id=' . $userId, $this->getExpireTime());
    }
}
